package org.bigk.invoices.dao;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.bigk.invoices.exceptions.DBAccessException;
import org.bigk.invoices.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;


@Repository("usersDAO")
public class UsersDAOImpl implements UsersDAO {

	private static final String USER_BY_LOGIN_QUERY = "SELECT u FROM User u WHERE u.login = :login";

	private static final Logger logger = LoggerFactory.getLogger(UsersDAOImpl.class);

	@PersistenceContext
	protected EntityManager em;

	@Override
	public User getUser(Long id) throws DBAccessException {
		logger.debug("getUser(id=[{}]) - start", id);
		
		User user = em.find(User.class, id);
		
		logger.debug("getUser() - end - return value=[{}]", user);
		return user;
	}

	@Override
	public User getUserByLogin(String login) throws DBAccessException {
		logger.debug("getUserByLogin(login=[{}]) - start", login);
		
		TypedQuery<User> query = em.createQuery(USER_BY_LOGIN_QUERY, User.class);
		query.setParameter("login", login);

        User user = null;
        try {
        	user = query.getSingleResult();
        } catch (NoResultException ex) {
        	logger.info("NoResultException caught, means that no user found for login [{}]", login);
        }
		
        logger.debug("getUserByLogin(String) - end - return value=[{}]", user);
        return user;
	}
}
